package cn.newtouch.pet.service.impl;

import cn.newtouch.basic.exception.BusinessException;
import cn.newtouch.basic.service.IBaiduAiAuditService;
import cn.newtouch.basic.service.impl.BaseServiceImpl;
import cn.newtouch.basic.util.CodeGenerateUtils;
import cn.newtouch.basic.util.DistanceUtils;
import cn.newtouch.basic.util.PageList;
import cn.newtouch.basic.util.Point;
import cn.newtouch.order.domain.OrderPetAcquisition;
import cn.newtouch.order.mapper.OrderPetAcquisitionMapper;
import cn.newtouch.org.domain.Employee;
import cn.newtouch.org.domain.Shop;
import cn.newtouch.org.mapper.EmployeeMapper;
import cn.newtouch.org.mapper.ShopMapper;
import cn.newtouch.pet.domain.Pet;
import cn.newtouch.pet.domain.SearchMasterMsg;
import cn.newtouch.pet.domain.SearchMasterMsgAuditLog;
import cn.newtouch.pet.dto.AcceptDto;
import cn.newtouch.pet.mapper.PetMapper;
import cn.newtouch.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.newtouch.pet.mapper.SearchMasterMsgMapper;
import cn.newtouch.pet.query.SearchMasterMsgQuery;
import cn.newtouch.pet.service.ISearchMasterMsgService;
import cn.newtouch.user.domain.User;
import cn.newtouch.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public void publish(SearchMasterMsg smm, Long id) {
        //1.将信息添加到数据库
        //user_id shop_id需要先set到smm
        //通过logininfoID获取user
        User user=userMapper.loadByLogininfoId(id);
        smm.setUser_id(user.getId());
        smm.setNote("待审核！");

        //通过百度地图工具类 获取距离发布消息地址最近的shop
        Point point = DistanceUtils.getPoint(smm.getAddress());
        Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
        smm.setShop_id(nearestShop.getId());

        searchMasterMsgMapper.save(smm);

        //2.审核
        Boolean textBl = baiduAiAuditService.textAudit(smm.getTitle()+smm.getAddress() + smm.getCoatColor() + smm.getName());

        Boolean imgBl = baiduAiAuditService.imageAudit(smm.getResources());

        if(textBl && imgBl){//3.审核通过
            //修改状态
            smm.setState(1);
            smm.setNote("待处理！");
            searchMasterMsgMapper.update(smm);
            //添加日志
            SearchMasterMsgAuditLog smmal = new SearchMasterMsgAuditLog();
            smmal.setState(1);
            smmal.setAuditTime(new Date());
            smmal.setMsgId(smm.getId());
            smmal.setNote("待处理！");
            //保存日志
            searchMasterMsgAuditLogMapper.save(smmal);

        }else{//4.审核不通过
            //修改状态
            smm.setNote("审核不通过,驳回!");
            searchMasterMsgMapper.update(smm);
            //添加日志
            SearchMasterMsgAuditLog smmal = new SearchMasterMsgAuditLog();
            smmal.setState(0);
            smmal.setAuditTime(new Date());
            smmal.setMsgId(smm.getId());
            smmal.setNote("审核不通过！");
            //保存日志
            searchMasterMsgAuditLogMapper.save(smmal);

            throw  new BusinessException("审核不通过，已驳回！！");
        }

    }

    /**
     * 待处理
     * @param query
     * @param id
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query, Long id) {
        //查询到emp
        Employee emp=employeeMapper.loadByLogininfoId(id);
        query.setState(1);
        //查询shopid 并set到query
        if(emp.getShop_id()!=null){
            //店铺人员
            query.setShopId(emp.getShop_id());
        }
        return super.queryPage(query);
    }

    /**
     * 用户信息
     * @param query
     * @param id
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, Long id) {
        //查询到userid
        User user = userMapper.loadByLogininfoId(id);
        query.setUserId(user.getId());
        //分页查询用户

        return super.queryPage(query);
    }

    /**
     * 待审核
     * @param query
     * @param id
     * @return
     */
    @Override
    public PageList<SearchMasterMsg> toAudit(SearchMasterMsgQuery query, Long id) {
        //查询到emp
        Employee emp=employeeMapper.loadByLogininfoId(id);
        query.setState(0);
        //查询shopid 并set到query
        if(emp.getShop_id()!=null){
            //店铺人员
            query.setShopId(emp.getShop_id());
        }
        return super.queryPage(query);
    }

    /**
     * 拒单
     * @param msgId
     */
    @Override
    public void reject(Long msgId) {
        searchMasterMsgMapper.reject(msgId);
    }

    /**
     * 接单
     * @param dto
     * @param id
     */
    @Override
    public void accept(AcceptDto dto, Long id) {
        //通过ssmid查询订单，判断是否为空，进行校验，以此判断是否已经被接单了
        OrderPetAcquisition order=orderPetAcquisitionMapper.loadBySmmid(dto.getMsgId());
        if(order!=null){
            throw new BusinessException("订单正在处理中，请另外接单！！！");
        }
        //生成一个pet
        //通过msgid查询searchMasterMsg
        SearchMasterMsg smm = searchMasterMsgMapper.loadById(dto.getMsgId());

        //再通过searchMasterMsg 生成一个PET
        Pet pet = searchMasterMsg2pet(smm);
        //保存pet
        petMapper.save(pet);

        //生成一个订单 需要准备订单的CRUD
        OrderPetAcquisition opa=initOrderPetAcquisition(pet,dto,smm);

        //保存orderPetAcquisition
        orderPetAcquisitionMapper.save(opa);
    }


    private OrderPetAcquisition initOrderPetAcquisition(Pet pet, AcceptDto dto, SearchMasterMsg smm) {

        OrderPetAcquisition oPa = new OrderPetAcquisition();

        //随机的订单编号 并set到对象中
        oPa.setOrderSn(CodeGenerateUtils.generateOrderSn(smm.getId()));

        oPa.setAddress(smm.getAddress());
        //摘要
        oPa.setDigest("【"+smm.getTitle()+"】");
        oPa.setEmp_id(dto.getHandler());
        //最迟处理订单时间 2天后
        oPa.setLastcomfirmtime(new Date(System.currentTimeMillis()+2*24*60*60*1000));
        oPa.setPet_id(pet.getId());
        oPa.setPrice(smm.getPrice());
        oPa.setShop_id(smm.getShop_id());
        oPa.setUser_id(smm.getUser_id());
        oPa.setState(0);
        oPa.setSearch_master_msg_id(smm.getId());

        return oPa;
    }

    private Pet searchMasterMsg2pet(SearchMasterMsg smm) {
        Pet pet = new Pet();

        pet.setName(smm.getName());
        pet.setResources(smm.getResources());
        pet.setCostprice(smm.getPrice());
        pet.setSearch_master_msg_id(smm.getId());
        pet.setShop_id(smm.getShop_id());
        pet.setType_id(smm.getPetType());

        return pet;
    }


}
